package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import com.auto.learning.R;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.BreakPointBean;
import com.auto.learning.bean.CaseType;
import com.auto.learning.bean.PlayChangeEvent;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.bean.ShareBean;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.fragment.AnchorFragment;
import com.auto.learning.fragment.CommentFragment;
import com.auto.learning.fragment.PlayFragment;
import com.auto.learning.fragment.ReadFragment;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FastBlur;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

@SuppressLint("NewApi")
public class PlayActivity extends FragmentActivity implements
		OnCheckedChangeListener, OnClickListener, Callback {

	private ImageView image_render;
	private View view;
	private RelativeLayout play_top, main_view;
	private PlayFragment playFragment;
	private ReadFragment readFragment;
	private CommentFragment commentFragment;
	private AnchorFragment anchorFragment;
	private Fragment currentFragment;
	public FragmentManager fm;
	private LinearLayout linear_share, linear_back;
	private int bookId;
	private RadioButton button_one, button_two;
	private int time = HttpRequestHelper.BLUR_DEFAULT_TIMES;
	private int type = 0; // 默认为0，直接到播放模式，1直接跳转到阅读模式, 2为评论列表,3为主播页面
	private int break_point_continue = 0; // 默认为0，为1时需要设置播放点在哪里和当前播放的章节
	private boolean isComment = false;
	// 是否拥有阅读模式 1否2是
	private int canRead = 2;
	// 判断是否能够购买
	private int needBuy;
	public int getNeedBuy() {
		return needBuy;
	}

	public void setNeedBuy(int needBuy) {
		this.needBuy = needBuy;
	}

	public int getCanRead() {
		return canRead;
	}

	public void setCanRead(int canRead) {
		this.canRead = canRead;
	}

	private Handle handler = new Handle(this) {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS:
				BookBean bean = (BookBean) msg.obj;
				if (bean != null) {
					playDialog(bean, 0);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				CommonMethod.makeNotice(PlayActivity.this, "登录成功");
				ResponeResult login_result = (ResponeResult) msg.obj;
				if (login_result != null) {
					EventBus.getEventBus("login_success_refreshUI").post(login_result);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(PlayActivity.this, msg.obj.toString());
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play);
		initView();
		initIntentData();
		initFragment();
		initData();
		registerEvent();
		TemporaryVariable.activities.push(this);
	}

	private void initView() {
		linear_back = (LinearLayout) findViewById(R.id.linear_back);
		linear_share = (LinearLayout) findViewById(R.id.linear_share);
		linear_back.setOnClickListener(this);
		linear_share.setOnClickListener(this);
		image_render = (ImageView) findViewById(R.id.image_render);
		view = findViewById(R.id.text);
		play_top = (RelativeLayout) findViewById(R.id.play_top);
		play_top.getBackground().setAlpha(127);
		main_view = (RelativeLayout) findViewById(R.id.main_view);
		applyBlur();
		button_one = (RadioButton) findViewById(R.id.button_one);
		button_two = (RadioButton) findViewById(R.id.button_two);
		TemporaryVariable.playActivity = this;
	}

	public void hideTop() {
		play_top.setVisibility(View.GONE);
	}

	public void showTop() {
		play_top.setVisibility(View.VISIBLE);
	}

	private void initIntentData() {
		Intent intent = getIntent();
		setBookId(intent.getIntExtra("bookId", 0));
		setCanRead(intent.getIntExtra("canRead", 2));
		setNeedBuy(intent.getIntExtra("needBuy", 1));
		String face_img = intent.getStringExtra("faceImg");
		ImageLoader.getInstance().displayImage(face_img, image_render);
		type = intent.getIntExtra("type", 0);
		break_point_continue = intent.getIntExtra("break_point_continue", 0);
		isComment = intent.getBooleanExtra("isComment", false);
	}

	private void initFragment() {
		fm = getSupportFragmentManager();
		playFragment = new PlayFragment();
		playFragment.setBookId(getBookId());
		playFragment.setBreakPointContinue(break_point_continue);
		readFragment = new ReadFragment();
		readFragment.setBookId(getBookId());
		commentFragment = new CommentFragment();
		commentFragment.setBookId(getBookId());
		anchorFragment = new AnchorFragment();
		anchorFragment.setBookId(getBookId());
		// readFragment.setComment(isComment);
	}

	private void initData() {
		if (type == 0) {
			currentFragment = playFragment;
			initFragment(currentFragment);
		} else if (type == 1) {
			button_two.setChecked(true);
			if (canRead == 2) {
				currentFragment = readFragment;
				initFragment(currentFragment);
			} else {
				currentFragment = commentFragment;
				initFragment(currentFragment);
			}

		} else if (type == 2) {
			button_two.setChecked(true);
			currentFragment = commentFragment;
			initFragment(currentFragment);
		}
		button_one.setOnCheckedChangeListener(this);
		button_two.setOnCheckedChangeListener(this);
	}

	private void initFragment(Fragment fragment) {
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.replace(R.id.main_view, fragment);
		transaction.commit();
	}

	public void switchContent(Fragment from, Fragment to) {
		if (to instanceof ReadFragment) {
			((ReadFragment) to).scrollView2Top();
		}
		if (currentFragment != to) {
			currentFragment = to;
			FragmentTransaction transaction = fm.beginTransaction();
			if (!to.isAdded()) { // 先判断是否被add过
				transaction.hide(from).add(R.id.main_view, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
			} else {
				transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
			}
		}
	}

	/***
	 * 处理高斯模糊
	 */
	public void applyBlur() {
		image_render.getViewTreeObserver().addOnPreDrawListener(
				new ViewTreeObserver.OnPreDrawListener() {
					@Override
					public boolean onPreDraw() {
						if (time > 0) {
							time--;
						} else {
							image_render.getViewTreeObserver().removeOnPreDrawListener(this);
						}
						image_render.buildDrawingCache();
						Bitmap bmp = image_render.getDrawingCache();
						FastBlur.blur(bmp, view, PlayActivity.this);
						return true;
					}
				});
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.button_one:
			if (canRead == 1) {
				switchContent(currentFragment, commentFragment);
			} else {
				if (type == 2) {
					switchContent(currentFragment, commentFragment);
				} else {
					switchContent(currentFragment, readFragment);
				}
			}
			break;
		case R.id.button_two:
			switchContent(currentFragment, playFragment);
			break;
		}
	}

	/**
	 * 切换到评论列表
	 */
	public void checkToComment() {
		type = 2;
		switchContent(currentFragment, commentFragment);
	}

	/**
	 * 切换到主播页面
	 */
	public void checkToAnchor() {
		type = 3;
		switchContent(currentFragment, anchorFragment);
	}

	/**
	 * 判断显示按钮
	 * 
	 * @param type
	 *            0.不显示，1，显示已下载，2.显示非vip需要购买的用户，3.显示免费书籍，4.显示vip用户下载按钮
	 * @return
	 */
	public List<CaseType> getTypeList(int userType) {
		List<CaseType> typelist = new ArrayList<CaseType>();
		CaseType type = new CaseType();
		switch (userType) {
		case 0:
			break;
		case 1:
			type.setText("已下载");
			type.setClick(null);
			type.setDrawable(R.drawable.btn_green);
			typelist.add(type);
			break;
		case 2:
			type.setText("购买本书");
			type.setClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String priceTag = "";
					String bookName="";
					if (currentFragment instanceof PlayFragment) {
						priceTag = playFragment.getListenModeBean().getPriceTag();
						bookName=playFragment.getListenModeBean().getBookName();
					}else if (currentFragment instanceof ReadFragment){
						bookName = readFragment.getReadModeBean().getBookName();
						priceTag = readFragment.getReadModeBean().getPriceTag();
					}else if (currentFragment instanceof CommentFragment) {
						bookName=  commentFragment.getReadModeBean().getBookName();
						priceTag = commentFragment.getReadModeBean().getPriceTag();
					}
					new UserBuyUtils(PlayActivity.this, getBookId(), priceTag, UserBuyUtils.OPERATOR_BUY,bookName).buy();
				}
			});
			type.setDrawable(R.drawable.wbtn);
			typelist.add(type);
			type = new CaseType();
			type.setText("订阅更多优惠");
			type.setClick(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(PlayActivity.this, SubscriptionActivity.class);
					startActivity(intent);
				}
			});
			type.setDrawable(R.drawable.btn_green);
			typelist.add(type);
			break;
		case 3:
		case 4:
			type.setText("下载");
			type.setClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					addDownload();
				}
			});
			type.setDrawable(R.drawable.btn_green);
			typelist.add(type);
			break;
		}
		return typelist;
	}

	private void addDownload() {
		if (playFragment != null && currentFragment instanceof PlayFragment) {
			playFragment.addDownload();
		} else if (readFragment != null && readFragment instanceof ReadFragment) {
			readFragment.addDownload();
		}
	}

	/**
	 * 切换到阅读模式
	 */
	public void checkToRead() {
		type = 1;
		switchContent(currentFragment, readFragment);
	}

	public ReadModeBean getReadModeFromReadFragment() {
		ReadModeBean readModeBean = null;
		if (readFragment != null) {
			readModeBean = readFragment.getReadModeBean();
		}
		return readModeBean;
	}

	public ReadModeBean getReadModeFromCommentFragment() {
		ReadModeBean readModeBean = null;
		if (commentFragment != null) {
			readModeBean = commentFragment.getReadModeBean();
		}
		return readModeBean;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.linear_share:
			ShareBean m_share = playFragment.getShareValue();
			if (m_share == null) {
				m_share = readFragment.getShareValue();
			}
			if (m_share == null) {
				return;
			}
			new ShareView(this, this).setTitle(m_share.getTitle()).setUrl(m_share.getUrl()).setContent(m_share.getContent()).setImageUrl(m_share.getImageUrl()).setId(bookId + "").show(findViewById(R.id.relative_main));
			break;
		case R.id.linear_back:
			finish();
			break;
		}
	}

	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		if (TemporaryVariable.playActivity != null) {
			TemporaryVariable.playActivity = null;
		}
		unRegisterEvent();
		super.onDestroy();
	}

	@Subscribe
	public void onEventPlayBeanChange(PlayChangeEvent event) {
		if (!TemporaryVariable.downLoadedList.contains(event.getBookId()) && CommonMethod.getNetworkState(this) == 0) {
			CommonMethod.makeNotice(this, getResources().getString(R.string.connect_err_io));
			return;
		}
		MusicPlayManager manager = MusicPlayManager.getInstance(this);
		if (event.getBookId() != bookId) {
			if (currentFragment instanceof PlayFragment) {
				ImageLoader.getInstance().displayImage(TextUtils.isEmpty(manager.getFaceImage()) ? "": manager.getFaceImage(), image_render);
				setBookId(event.getBookId());
				playFragment.setBookId(event.getBookId());
				readFragment.setBookId(event.getBookId());
				if (playFragment.getListenModeBean() != null && playFragment.getListenModeBean().getBookId() != 0) {
					playFragment.refreData();
				}
				if (readFragment.getReadModeBean() != null && readFragment.getReadModeBean().getBookId() != 0) {
					readFragment.refreData();
				}
			} else {
				try {
					if (playFragment != null && playFragment.getBookId() > 0) {
						playFragment.updateUi();
					}
					if (readFragment != null && readFragment.getBookId() > 0) {
						readFragment.updateUi();
					}
					if (commentFragment != null && commentFragment.getBookId() > 0) {
						commentFragment.updateUi();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void registerEvent() {
		EventBus.getEventBus("m_play_bookbean_change", ThreadEnforcer.MAIN)
				.register(this);
	}

	public void unRegisterEvent() {
		EventBus.getEventBus("m_play_bookbean_change", ThreadEnforcer.MAIN)
				.unregister(this);
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(PlayActivity.this, msg);
		return false;
	}

	public void getLocalBook(BookBean bookBean) {
		if (bookBean != null && bookBean.getSectionList() != null
				&& bookBean.getSectionList().size() > 0) {
			handler.obtainMessage(HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS,
					bookBean).sendToTarget();
		} else {
			Cache.getBookBeanById(PlayActivity.this, bookId, handler);
		}
	}

	/***
	 * 获取被评论书的信息
	 */
	public Map<String, Object> getCommentBookInfo() {
		Map<String, Object> map = readFragment.getCommentBookInfo();
		if (map != null && map.size() == 0) {
			map = playFragment.getCommentBookInfo();
		}
		return map;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode,
			final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(PlayActivity.this,
							data.getStringExtra("userId"),
							data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"),
							data.getBooleanExtra("isweixin", false), handler);
				}
			});
		} else if (requestCode == 100 && resultCode == 204) {
			EventBus.getEventBus("login_refreshUI").post(
					new LoginSuccessEvent());
		}
	}

	/**
	 * 更新背景图
	 * 
	 * @param imageUrl
	 */
	public void updateBackImage(String imageUrl) {
		if (!TextUtils.isEmpty(imageUrl)) {
			ImageLoader.getInstance().displayImage(imageUrl, image_render);
			time = HttpRequestHelper.BLUR_DEFAULT_TIMES;
			applyBlur();
		}
	}

	public void showDialog(final BookBean bookBean, final int position,
			final int flag) {
		CommonAlertDialog alertDialog = new CommonAlertDialog(PlayActivity.this);
		int size = 0;
		if (bookBean.getSectionList() != null) {
			List<SelectionVo> vo_list = bookBean.getSectionList();
			for (SelectionVo eleme : vo_list) {
				size += eleme.getDoubiSize() + eleme.getProSize()
						+ eleme.getEnSize();
			}
		}
		alertDialog.setTextMessage(String.format(
				getResources().getString(R.string.play_size_notice),
				CommonMethod.calculationNum(size)));
		alertDialog.setShowTitle(true);
		String[] a = { getResources().getString(R.string.app_continue),
				getResources().getString(R.string.app_cancel) };
		alertDialog.setBtns(new DialogListener() {

			@Override
			public void okButtonClick(Dialog dialog) {
				play(bookBean, bookBean.getSectionList().get(position)
						.getSectionId(), true, flag);
				MusicPlayManager.getInstance(PlayActivity.this).setShowNetTips(
						false);
				dialog.dismiss();
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				dialog.dismiss();
				CommonMethod.reordPlayStatus(PlayActivity.this,
						bookBean.getBookId(), true);
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				dialog.dismiss();
				CommonMethod.reordPlayStatus(PlayActivity.this,
						bookBean.getBookId(), true);
			}
		}, a);
		alertDialog.show();
	}

	public void playDialog(final BookBean bookBean, int position, int flag) {
		try {
			if (TemporaryVariable.downLoadedList.contains(bookBean.getBookId())) {
				play(bookBean, bookBean.getSectionList().get(position)
						.getSectionId(), true, flag);
			} else {
				if ((boolean) SharedPreferencesUtils.getParam(PlayActivity.this,HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {play(bookBean, bookBean.getSectionList().get(position).getSectionId(), true, flag);
				} else {
					switch (CommonMethod.getNetworkState(PlayActivity.this)) {
					case 0:
						CommonMethod.makeNotice(PlayActivity.this,getResources().getString(R.string.connect_err_io));
						EventBus.getEventBus("m_play_stute").post(false);
						break;
					case 1:
						play(bookBean, bookBean.getSectionList().get(position).getSectionId(), true, flag);
						break;
					case 2:
						showDialog(bookBean, position, flag);
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void playDialog(BookBean bookBean, int position) {
		playDialog(bookBean, position, 0);
	}

	private void play(final BookBean bookBean, final int selectId,
			final boolean isWifi, final int flag) {
		handler.postDelayed(new Runnable() {
			public void run() {
				ArrayList<BookBean> m_list = new ArrayList<BookBean>();
				if (isWifi) {
					m_list.add(bookBean);
				}
				if (flag == 0) {
					MusicPlayManager.getInstance(PlayActivity.this).setNeedContinue(true).setPlayList(m_list).setBookId(bookBean.getBookId()).play();
				} else if (flag == 1) {
					BreakPointBean breakPointBean = TemporaryVariable.breakPiontMap.get(bookId);
					boolean m_flag = false;
					if (breakPointBean != null&& breakPointBean.getChapterId() == selectId) {
						m_flag = true;
					}
					MusicPlayManager.getInstance(PlayActivity.this).setPlayList(m_list).setNeedContinue(m_flag).setBookId(bookBean.getBookId()).setChapterId(selectId).play();
				}
			}
		}, 1500);
		Intent intent = new Intent(PlayActivity.this, PlayActivity.class);
		intent.putExtra("bookId", bookBean.getBookId());
		intent.putExtra("faceImg", bookBean.getFaceImg());
		intent.putExtra("canRead", bookBean.getCanRead());
		intent.putExtra("needBuy", bookBean.getNeedBuy());
		startActivity(intent);
	}

}
